<template>
  <div class="report-export-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>数据导出与报表生成</h3>
          <div class="header-actions">
            <el-button type="primary" @click="showExportDialog">
              <el-icon><Download /></el-icon>
              快速导出
            </el-button>
            <el-button type="success" @click="showReportDialog">
              <el-icon><Document /></el-icon>
              生成报表
            </el-button>
            <el-button type="warning" @click="showScheduleDialog">
              <el-icon><Clock /></el-icon>
              定时任务
            </el-button>
          </div>
        </div>
      </template>

      <!-- 导出历史 -->
      <div class="export-history">
        <h4>导出历史</h4>
        <el-table :data="exportHistory" border stripe>
          <el-table-column prop="name" label="文件名" width="200" />
          <el-table-column prop="type" label="类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getTypeTagType(row.type)">{{ row.type }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="size" label="文件大小" width="120" />
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)">{{ row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="downloadFile(row)" :disabled="row.status !== '完成'">
                下载
              </el-button>
              <el-button type="danger" size="small" @click="deleteFile(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 报表模板 -->
      <div class="report-templates">
        <h4>报表模板</h4>
        <el-row :gutter="20">
          <el-col :span="8" v-for="template in reportTemplates" :key="template.id">
            <el-card class="template-card" @click="selectTemplate(template)">
              <div class="template-content">
                <div class="template-icon">
                  <el-icon size="32"><component :is="template.icon" /></el-icon>
                </div>
                <div class="template-info">
                  <h5>{{ template.name }}</h5>
                  <p>{{ template.description }}</p>
                  <div class="template-tags">
                    <el-tag v-for="tag in template.tags" :key="tag" size="small">{{ tag }}</el-tag>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 导出对话框 -->
    <el-dialog
      v-model="exportDialogVisible"
      title="数据导出"
      width="600px"
    >
      <el-form :model="exportForm" :rules="exportRules" ref="exportFormRef" label-width="120px">
        <el-form-item label="导出类型" prop="type">
          <el-select v-model="exportForm.type" @change="handleExportTypeChange" style="width: 100%">
            <el-option label="Excel文件" value="excel" />
            <el-option label="CSV文件" value="csv" />
            <el-option label="PDF文件" value="pdf" />
            <el-option label="JSON文件" value="json" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="数据范围" prop="dataRange">
          <el-select v-model="exportForm.dataRange" @change="handleDataRangeChange" style="width: 100%">
            <el-option label="全部数据" value="all" />
            <el-option label="当前筛选" value="filtered" />
            <el-option label="自定义范围" value="custom" />
          </el-select>
        </el-form-item>
        
        <el-form-item v-if="exportForm.dataRange === 'custom'" label="时间范围" prop="dateRange">
          <el-date-picker
            v-model="exportForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="导出字段" prop="fields">
          <el-checkbox-group v-model="exportForm.fields">
            <el-checkbox 
              v-for="field in availableFields" 
              :key="field.key"
              :label="field.key"
            >
              {{ field.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item label="文件名" prop="fileName">
          <el-input v-model="exportForm.fileName" placeholder="请输入文件名" />
        </el-form-item>
        
        <el-form-item label="导出选项">
          <el-checkbox v-model="exportForm.includeHeader">包含表头</el-checkbox>
          <el-checkbox v-model="exportForm.includeSummary">包含汇总</el-checkbox>
          <el-checkbox v-model="exportForm.includeCharts">包含图表</el-checkbox>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="exportDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="startExport" :loading="exportLoading">
          开始导出
        </el-button>
      </template>
    </el-dialog>

    <!-- 报表生成对话框 -->
    <el-dialog
      v-model="reportDialogVisible"
      title="生成报表"
      width="700px"
    >
      <el-form :model="reportForm" :rules="reportRules" ref="reportFormRef" label-width="120px">
        <el-form-item label="报表类型" prop="type">
          <el-select v-model="reportForm.type" @change="handleReportTypeChange" style="width: 100%">
            <el-option label="销售日报" value="daily" />
            <el-option label="销售周报" value="weekly" />
            <el-option label="销售月报" value="monthly" />
            <el-option label="销售年报" value="yearly" />
            <el-option label="自定义报表" value="custom" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="报表名称" prop="name">
          <el-input v-model="reportForm.name" placeholder="请输入报表名称" />
        </el-form-item>
        
        <el-form-item label="报表时间" prop="reportDate">
          <el-date-picker
            v-model="reportForm.reportDate"
            type="date"
            placeholder="选择报表日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="报表内容" prop="content">
          <el-checkbox-group v-model="reportForm.content">
            <el-checkbox label="sales">销售数据</el-checkbox>
            <el-checkbox label="products">商品分析</el-checkbox>
            <el-checkbox label="customers">客户分析</el-checkbox>
            <el-checkbox label="cashiers">收银员分析</el-checkbox>
            <el-checkbox label="payments">支付分析</el-checkbox>
            <el-checkbox label="trends">趋势分析</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item label="报表格式" prop="format">
          <el-radio-group v-model="reportForm.format">
            <el-radio label="pdf">PDF格式</el-radio>
            <el-radio label="excel">Excel格式</el-radio>
            <el-radio label="html">HTML格式</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="报表模板" prop="template">
          <el-select v-model="reportForm.template" placeholder="选择报表模板" style="width: 100%">
            <el-option label="标准模板" value="standard" />
            <el-option label="详细模板" value="detailed" />
            <el-option label="简洁模板" value="simple" />
            <el-option label="自定义模板" value="custom" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="发送方式">
          <el-checkbox v-model="reportForm.email">邮件发送</el-checkbox>
          <el-checkbox v-model="reportForm.download">直接下载</el-checkbox>
        </el-form-item>
        
        <el-form-item v-if="reportForm.email" label="收件人" prop="recipients">
          <el-input 
            v-model="reportForm.recipients" 
            type="textarea" 
            :rows="3"
            placeholder="请输入收件人邮箱，多个邮箱用逗号分隔"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="reportDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="generateReport" :loading="reportLoading">
          生成报表
        </el-button>
      </template>
    </el-dialog>

    <!-- 定时任务对话框 -->
    <el-dialog
      v-model="scheduleDialogVisible"
      title="定时任务设置"
      width="600px"
    >
      <el-form :model="scheduleForm" :rules="scheduleRules" ref="scheduleFormRef" label-width="120px">
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="scheduleForm.name" placeholder="请输入任务名称" />
        </el-form-item>
        
        <el-form-item label="任务类型" prop="type">
          <el-select v-model="scheduleForm.type" @change="handleScheduleTypeChange" style="width: 100%">
            <el-option label="数据导出" value="export" />
            <el-option label="报表生成" value="report" />
            <el-option label="数据备份" value="backup" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="执行频率" prop="frequency">
          <el-select v-model="scheduleForm.frequency" @change="handleFrequencyChange" style="width: 100%">
            <el-option label="每日" value="daily" />
            <el-option label="每周" value="weekly" />
            <el-option label="每月" value="monthly" />
            <el-option label="自定义" value="custom" />
          </el-select>
        </el-form-item>
        
        <el-form-item v-if="scheduleForm.frequency === 'daily'" label="执行时间" prop="time">
          <el-time-picker
            v-model="scheduleForm.time"
            placeholder="选择执行时间"
            format="HH:mm"
            value-format="HH:mm"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item v-if="scheduleForm.frequency === 'weekly'" label="执行日期" prop="weekday">
          <el-select v-model="scheduleForm.weekday" placeholder="选择星期" style="width: 100%">
            <el-option label="星期一" value="1" />
            <el-option label="星期二" value="2" />
            <el-option label="星期三" value="3" />
            <el-option label="星期四" value="4" />
            <el-option label="星期五" value="5" />
            <el-option label="星期六" value="6" />
            <el-option label="星期日" value="0" />
          </el-select>
        </el-form-item>
        
        <el-form-item v-if="scheduleForm.frequency === 'monthly'" label="执行日期" prop="day">
          <el-input-number
            v-model="scheduleForm.day"
            :min="1"
            :max="31"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="任务状态" prop="status">
          <el-switch v-model="scheduleForm.status" active-text="启用" inactive-text="禁用" />
        </el-form-item>
        
        <el-form-item label="任务描述" prop="description">
          <el-input 
            v-model="scheduleForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入任务描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="scheduleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveSchedule" :loading="scheduleLoading">
          保存任务
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const exportDialogVisible = ref(false)
const reportDialogVisible = ref(false)
const scheduleDialogVisible = ref(false)
const exportLoading = ref(false)
const reportLoading = ref(false)
const scheduleLoading = ref(false)

// 表单引用
const exportFormRef = ref()
const reportFormRef = ref()
const scheduleFormRef = ref()

// 导出表单
const exportForm = reactive({
  type: 'excel',
  dataRange: 'all',
  dateRange: [],
  fields: [],
  fileName: '',
  includeHeader: true,
  includeSummary: true,
  includeCharts: false
})

// 报表表单
const reportForm = reactive({
  type: 'daily',
  name: '',
  reportDate: '',
  content: ['sales'],
  format: 'pdf',
  template: 'standard',
  email: false,
  download: true,
  recipients: ''
})

// 定时任务表单
const scheduleForm = reactive({
  name: '',
  type: 'export',
  frequency: 'daily',
  time: '02:00',
  weekday: '1',
  day: 1,
  status: true,
  description: ''
})

// 可用字段
const availableFields = ref([
  { key: 'date', name: '日期' },
  { key: 'cashier', name: '收银员' },
  { key: 'product', name: '商品' },
  { key: 'category', name: '分类' },
  { key: 'customer', name: '客户' },
  { key: 'paymentMethod', name: '支付方式' },
  { key: 'amount', name: '金额' },
  { key: 'quantity', name: '数量' },
  { key: 'profit', name: '利润' },
  { key: 'orderCount', name: '订单数' }
])

// 导出历史
const exportHistory = ref([
  {
    id: 1,
    name: '销售数据_20240115.xlsx',
    type: 'Excel',
    size: '2.5MB',
    createTime: '2024-01-15 14:30:00',
    status: '完成'
  },
  {
    id: 2,
    name: '商品分析_20240114.pdf',
    type: 'PDF',
    size: '1.8MB',
    createTime: '2024-01-14 16:45:00',
    status: '完成'
  },
  {
    id: 3,
    name: '客户数据_20240113.csv',
    type: 'CSV',
    size: '856KB',
    createTime: '2024-01-13 10:20:00',
    status: '完成'
  },
  {
    id: 4,
    name: '销售报表_20240112.xlsx',
    type: 'Excel',
    size: '3.2MB',
    createTime: '2024-01-12 18:00:00',
    status: '处理中'
  }
])

// 报表模板
const reportTemplates = ref([
  {
    id: 1,
    name: '销售日报',
    description: '包含当日销售数据、商品排行、收银员业绩等',
    icon: 'Document',
    tags: ['日报', '销售', '业绩']
  },
  {
    id: 2,
    name: '商品分析报告',
    description: '商品销售分析、库存状况、利润分析等',
    icon: 'Box',
    tags: ['商品', '分析', '库存']
  },
  {
    id: 3,
    name: '客户分析报告',
    description: '客户消费行为、会员分析、客户价值等',
    icon: 'User',
    tags: ['客户', '会员', '价值']
  },
  {
    id: 4,
    name: '收银员业绩报告',
    description: '收银员工作效率、业绩对比、培训建议等',
    icon: 'UserFilled',
    tags: ['收银员', '业绩', '效率']
  },
  {
    id: 5,
    name: '财务分析报告',
    description: '收入支出、利润分析、成本控制等',
    icon: 'Money',
    tags: ['财务', '利润', '成本']
  },
  {
    id: 6,
    name: '综合运营报告',
    description: '全面运营数据分析、趋势预测、改进建议等',
    icon: 'TrendCharts',
    tags: ['综合', '运营', '趋势']
  }
])

// 表单验证规则
const exportRules = {
  type: [
    { required: true, message: '请选择导出类型', trigger: 'change' }
  ],
  dataRange: [
    { required: true, message: '请选择数据范围', trigger: 'change' }
  ],
  fields: [
    { required: true, message: '请选择导出字段', trigger: 'change' }
  ],
  fileName: [
    { required: true, message: '请输入文件名', trigger: 'blur' }
  ]
}

const reportRules = {
  type: [
    { required: true, message: '请选择报表类型', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入报表名称', trigger: 'blur' }
  ],
  reportDate: [
    { required: true, message: '请选择报表日期', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请选择报表内容', trigger: 'change' }
  ]
}

const scheduleRules = {
  name: [
    { required: true, message: '请输入任务名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择任务类型', trigger: 'change' }
  ],
  frequency: [
    { required: true, message: '请选择执行频率', trigger: 'change' }
  ]
}

// 方法
const getTypeTagType = (type) => {
  const typeMap = {
    'Excel': 'success',
    'PDF': 'danger',
    'CSV': 'warning',
    'JSON': 'info'
  }
  return typeMap[type] || 'info'
}

const getStatusTagType = (status) => {
  const statusMap = {
    '完成': 'success',
    '处理中': 'warning',
    '失败': 'danger'
  }
  return statusMap[status] || 'info'
}

const showExportDialog = () => {
  exportDialogVisible.value = true
  // 设置默认文件名
  const today = new Date().toISOString().split('T')[0]
  exportForm.fileName = `销售数据_${today}`
  // 设置默认字段
  exportForm.fields = ['date', 'cashier', 'product', 'amount', 'quantity']
}

const showReportDialog = () => {
  reportDialogVisible.value = true
  // 设置默认报表名称
  const today = new Date().toISOString().split('T')[0]
  reportForm.name = `销售报表_${today}`
  reportForm.reportDate = today
}

const showScheduleDialog = () => {
  scheduleDialogVisible.value = true
}

const handleExportTypeChange = () => {
  // 根据导出类型调整默认选项
  if (exportForm.type === 'pdf') {
    exportForm.includeCharts = true
  } else {
    exportForm.includeCharts = false
  }
}

const handleDataRangeChange = () => {
  if (exportForm.dataRange === 'custom') {
    // 设置默认时间范围
    const today = new Date()
    const lastWeek = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)
    exportForm.dateRange = [
      lastWeek.toISOString().split('T')[0],
      today.toISOString().split('T')[0]
    ]
  }
}

const handleReportTypeChange = () => {
  // 根据报表类型设置默认内容
  const contentMap = {
    'daily': ['sales', 'products', 'cashiers'],
    'weekly': ['sales', 'products', 'customers', 'trends'],
    'monthly': ['sales', 'products', 'customers', 'cashiers', 'payments', 'trends'],
    'yearly': ['sales', 'products', 'customers', 'cashiers', 'payments', 'trends'],
    'custom': ['sales']
  }
  reportForm.content = contentMap[reportForm.type] || ['sales']
}

const handleScheduleTypeChange = () => {
  // 根据任务类型设置默认描述
  const descriptionMap = {
    'export': '定时导出销售数据',
    'report': '定时生成销售报表',
    'backup': '定时备份系统数据'
  }
  scheduleForm.description = descriptionMap[scheduleForm.type] || ''
}

const handleFrequencyChange = () => {
  // 根据频率设置默认时间
  if (scheduleForm.frequency === 'daily') {
    scheduleForm.time = '02:00'
  } else if (scheduleForm.frequency === 'weekly') {
    scheduleForm.weekday = '1'
  } else if (scheduleForm.frequency === 'monthly') {
    scheduleForm.day = 1
  }
}

const startExport = async () => {
  if (!exportFormRef.value) return
  
  try {
    await exportFormRef.value.validate()
    exportLoading.value = true
    
    // 模拟导出过程
    await new Promise(resolve => setTimeout(resolve, 3000))
    
    // 添加到导出历史
    const newExport = {
      id: Date.now(),
      name: `${exportForm.fileName}.${exportForm.type === 'excel' ? 'xlsx' : exportForm.type}`,
      type: exportForm.type === 'excel' ? 'Excel' : exportForm.type.toUpperCase(),
      size: '2.1MB',
      createTime: new Date().toLocaleString(),
      status: '完成'
    }
    exportHistory.value.unshift(newExport)
    
    ElMessage.success('数据导出成功')
    exportDialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    exportLoading.value = false
  }
}

const generateReport = async () => {
  if (!reportFormRef.value) return
  
  try {
    await reportFormRef.value.validate()
    reportLoading.value = true
    
    // 模拟报表生成过程
    await new Promise(resolve => setTimeout(resolve, 5000))
    
    ElMessage.success('报表生成成功')
    reportDialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    reportLoading.value = false
  }
}

const saveSchedule = async () => {
  if (!scheduleFormRef.value) return
  
  try {
    await scheduleFormRef.value.validate()
    scheduleLoading.value = true
    
    // 模拟保存过程
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    ElMessage.success('定时任务保存成功')
    scheduleDialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    scheduleLoading.value = false
  }
}

const selectTemplate = (template) => {
  ElMessage.info(`选择了模板: ${template.name}`)
  // 这里可以根据模板设置报表表单
}

const downloadFile = (file) => {
  ElMessage.success(`开始下载: ${file.name}`)
}

const deleteFile = async (file) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除文件 "${file.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = exportHistory.value.findIndex(item => item.id === file.id)
    if (index > -1) {
      exportHistory.value.splice(index, 1)
      ElMessage.success('文件删除成功')
    }
  } catch {
    // 用户取消删除
  }
}

// 生命周期
onMounted(() => {
  // 初始化数据
})
</script>

<style scoped>
.report-export-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.export-history {
  margin-bottom: 30px;
}

.export-history h4 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.report-templates h4 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.template-card {
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 16px;
}

.template-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.template-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.template-icon {
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.template-info {
  flex: 1;
}

.template-info h5 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.template-info p {
  margin: 0 0 12px 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.4;
}

.template-tags {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .template-content {
    flex-direction: column;
    text-align: center;
  }
  
  .template-icon {
    width: 50px;
    height: 50px;
  }
  
  .template-info h5 {
    font-size: 14px;
  }
  
  .template-info p {
    font-size: 12px;
  }
}
</style>
